﻿namespace EasyGo.Data.QueryServices
{
    using System.Collections.Generic;
    using System.Linq;

    using EasyGo.Common.Dto;
    using EasyGo.Common.Queries;
    using EasyGo.Logic.Model;

    public class ProjectQueries : IProjectQueries
    {
        private readonly ApplicationDbContext context;

        public ProjectQueries(ApplicationDbContext context)
        {
            this.context = context;
        }

        public IEnumerable<ListProjectDto> GetAllProjects()
        {
            return from p in this.context.Projects
                   join c in this.context.Customers on p.CustomerId equals c.Id
                   orderby p.AddDate descending
                   select
                       new ListProjectDto()
                       {
                           CreateDate = p.AddDate,
                           CustomerId = p.CustomerId,
                           CustomerName = c.Name,
                           Name = p.Name,
                           Deadline = p.Deadline,
                           Id = p.Id
                       };
        }

        public ProjectDto FindProject(int id)
        {
            return (from p in this.context.Projects
                    join c in this.context.Customers on p.CustomerId equals c.Id
                    where p.Id == id
                    select
                        new ProjectDto
                            {
                                CustomerId = p.CustomerId,
                                Deadline = p.Deadline,
                                Description = p.Description,
                                Id = p.Id,
                                Name = p.Name,
                                CustomerName = c.Name
                            }).SingleOrDefault();
        }

        public IEnumerable<LookupDto> GetLookup(string term)
        {
            IQueryable<Project> query = this.context.Projects.OrderByDescending(x => x.AddDate);
            if (!string.IsNullOrEmpty(term))
            {
                query = query.Where(x => x.Name.StartsWith(term));
            }

            return query.Take(10).Select(x => new LookupDto { Id = x.Id, Text = x.Name });
        }
    }
}
